﻿using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Web.Routing;

public static class HtmlHelperExtensions
{
    private const string defaultPageTitle = "NOSDC - ";

    public static MvcHtmlString CreateMetaDescription(this HtmlHelper helper, string description)
    {
        return MvcHtmlString.Create(String.Format("<meta name=\"description\" content=\"{0}\">", description));
    }

    public static string CreatePageTitle(this HtmlHelper helper, string title)
    {
        return defaultPageTitle + title;
    }
    
    public static MvcHtmlString MenuLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)
    {
        var currentController = helper.ViewContext.RouteData.GetRequiredString("controller");

        if (controllerName == currentController)
        {
            return helper.ActionLink(
                linkText,
                actionName,
                controllerName,
                null,
                new
                {
                    @class = "selected"
                });
        }

        return helper.ActionLink(linkText, actionName, controllerName);
    }

    public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty[]>> expression, MultiSelectList multiSelectList, object htmlAttributes = null)
    {
        var body = expression.Body as MemberExpression;
        string propertyName = body.Member.Name;

        var list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
        var selectedValues = new List<string>();

        if (list != null)
        {
            selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString());
        }

        var divTag = new TagBuilder("div");
        divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

        foreach (var item in multiSelectList)
        {
            divTag.InnerHtml += String.Format("<div><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" " +
                                                "value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></div>",
                                                propertyName,
                                                item.Value,
                                                selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
                                                item.Text);
        }

        return MvcHtmlString.Create(divTag.ToString());
    }
}